package org.xydpeng.framework.l2cache.support;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.xydpeng.framework.l2cache.serialization.DelegatedRedisSerializer;
import org.xydpeng.framework.l2cache.serialization.KryoSerialization;
import org.xydpeng.framework.l2cache.serialization.Serialization;

import java.util.Objects;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2024/6/12
 * @description:
 */
public class RedisSerializerFactory {

    public static RedisSerializer createInstance(String type) {
        RedisSerializer redisSerializer = null;
        type = Objects.isNull(type) ? "" : type.toLowerCase();
        switch (type) {
            case "kryo":
                redisSerializer = new DelegatedRedisSerializer(new KryoSerialization());
                break;
            default:
                ObjectMapper om = new ObjectMapper();
                om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
                om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
                // 启用反序列化特性
                om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                redisSerializer = new Jackson2JsonRedisSerializer(om, Object.class);
                break;
        }
        return redisSerializer;
    }


}
